# CodeSkulptor runs Python programs in your browser.
# Click the upper left button to run this simple demo.

# CodeSkulptor runs in Chrome 18+, Firefox 11+, and Safari 6+.
# Some features may work in other browsers, but do not expect
# full functionality.  It does NOT run in Internet Explorer.

import simplegui
import math

message = "Drag a curve to create trajectory"

points=[]


def move_func(fwd):
    if fwd:
       return "smooth_fwd"
    return "smooth_bak"

# Handler for mouse click
def printTraj(lpoints,fwd):
    global message
    message = "See console!"
    p0=None
    p00=None
    
    for p in lpoints:
        alpha=0
        if p00!=None:
            alphaPrev=math.atan2(p0[0]-p00[0],p0[1]-p00[1])/math.pi*180
            alphaNext=math.atan2(p[0]-p0[0],p[1]-p0[1])/math.pi*180
            alpha = int(alphaNext - alphaPrev)
            if alpha>180:
               alpha = alpha-360
            if alpha<-180:
               alpha = alpha+360
        if p0!=None:
            if alpha>90:
                alpha -= 180
                fwd = not fwd
            if alpha<-90:
                alpha += 180
                fwd = not fwd
            print move_func(fwd)+"(",alpha,");"
        p00=p0
        p0=p
    return fwd    
        
def dist(p0,p):
    return math.sqrt((p0[0]-p[0])**2+(p0[1]-p[1])**2)

def printTrajectory():
    ps = list(points)
    fwd=printTraj(ps,True);
    ps.reverse()
    printTraj(ps,not fwd);
    

# Handler to draw on canvas
def draw(canvas):
    canvas.draw_text(message, [50,112], 48, "Red")
    p0=None
    for p in points:
        canvas.draw_circle(p, 4, 1, 'white')
        if p0!=None:
            canvas.draw_line(p0, p, 2, 'Red')
        p0=p
    
def mouse_handler(position):
    if len(points)==0:
        points.append(position)
        return
    
    seg=20
    if dist(position,points[len(points)-1])>=seg:
       k = seg / dist(position,points[len(points)-1])
       x = points[len(points)-1][0]*(1-k)+position[0]*k
       y = points[len(points)-1][1]*(1-k)+position[1]*k
       points.append((x,y))
   


# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Home", 800, 600)
frame.add_button("Print trajectory", printTrajectory)
frame.set_draw_handler(draw)
frame.set_mousedrag_handler(mouse_handler)    

# Start the frame animation
frame.start()

